<template>
  <view>
    <view>
      <u-form :model="param" ref="uQueryForm">
        <u-row>
          <u-col span="2">
            <u--text type="primary" text="扫码"></u--text>
          </u-col>
          <u-col span="8">
            <u--input
                placeholder="请扫码"
                border="surround"
                v-model="param.searchKey"
                :readonly="initFlag"
                clearable
            ></u--input>
          </u-col>
        </u-row>

        <u-row v-show="false">
          <u-col span="2">
            <u--text type="primary" text="物料编码"></u--text>
          </u-col>
          <u-col span="8">
            <u--input
                placeholder="请输入物料编码"
                border="surround"
                v-model="param.invCode"
                clearable
            ></u--input>
          </u-col>
        </u-row>

        <u-row v-show="false">
          <u-col span="2">
            <u--text type="primary" text="采购订单"></u--text>
          </u-col>
          <u-col span="8">
            <u--input
                placeholder="请输入采购订单"
                border="surround"
                v-model="param.orderNo"
                clearable
            ></u--input>
          </u-col>
        </u-row>

        <u-row v-show="false">
          <u-col span="2">
            <u--text type="primary" text="供应商"></u--text>
          </u-col>
          <u-col span="8">
            <u--input
                placeholder="请输入供应商"
                border="surround"
                v-model="param.suppLierName"
                clearable
            ></u--input>
          </u-col>
        </u-row>
      </u-form>
      <u-divider text="分割线" :dot="true"></u-divider>
    </view>

    <u-list @scrolltolower="scrollTolower"  @scrollWithAnimation="true" :key="listKey">
      <u-list-item v-for="(item, index) in items" :key="index" class="custom-list-item" >
        <view @longpress="handleLongPress(item)">
          <u-cell :title="`供应商：${item.supplierName}`"></u-cell>
          <u-cell :title="`订单号：${item.orderNo}`"></u-cell>
          <u-cell :title="`物料编码：${item.invCode}`"></u-cell>
          <u-cell :title="`物料名称：${item.invName}`"></u-cell>
          <u-cell :title="`收货数量：${item.actQty}`"></u-cell>
          <u-cell :title="`收货时间：${formatDate(item.actRecevingDate)}`"></u-cell>
          <u-cell :title="`任务号：${item.taskNo}`"></u-cell>
        </view>
      </u-list-item>
    </u-list>

    <u-loading-icon :show="loading" text="加载中" textSize="18"></u-loading-icon>

    <view class="fixed-bottom">
      <u-button @click="scanCode">扫码收货</u-button>
    </view>
  </view>
</template>
<script >
import UButton from "../../../../uview-ui/components/u-button/u-button.vue";
import UForm from "../../../../uview-ui/components/u--form/u--form.vue";
import UniDataSelect from "../../../../uni_modules/uni-data-select/components/uni-data-select/uni-data-select.vue";
import UInput from "../../../../uview-ui/components/u--input/u--input.vue";
import URow from "../../../../uview-ui/components/u-row/u-row.vue";
import UCol from "../../../../uview-ui/components/u-col/u-col.vue";
import UFormItem from "../../../../uview-ui/components/u-form-item/u-form-item.vue";
import UList from "../../../../uview-ui/components/u-list/u-list.vue";
import UListItem from "../../../../uview-ui/components/u-list-item/u-list-item.vue";
import UCell from "../../../../uview-ui/components/u-cell/u-cell.vue";
import {cancelAsn, getRecevings} from "@/api/work/wareHourse/asnTask";
import ULoadingIcon from "../../../../uview-ui/components/u-loading-icon/u-loading-icon.vue";
import UModal from "../../../../uview-ui/components/u-modal/u-modal.vue";
import UCalendar from "../../../../uview-ui/components/u-calendar/u-calendar.vue";
import {formatDate} from "@/api/work/utils";
import UDivider from "../../../../uview-ui/components/u-divider/u-divider.vue";

export default {
  components: {
    UDivider,
    UCalendar, UModal,
    ULoadingIcon,
    UCell, UListItem, UList,
    UFormItem,
    UCol, URow, UInput, UniDataSelect,
    UForm,
    UButton
  },
  data() {
    return {
      items: [],
      listKey: Date.now(),
      param: {
        pageNum: 0,
        pageSize: 10,
        invCode: null,
        batchNo: null,
        suppLierName: null,
        orderNo: null,
        productionDate: null,
      },
      loading: false,
      confirmDisabled: true,
      handlePdaScan: null,
      initFlag: false,
    };
  },
  onLoad() {
    try {
      this.initScan();
      this.initFlag = true;
    } catch (e) {
      this.$modal.showToast('该类型设备暂不支持红外扫码', e)
    }
  },
  beforeDestroy() {
    if (this.initFlag) {
      let globalEvent = uni.requireNativePlugin('globalEvent');
      globalEvent.removeEventListener('iDataBarcodeEvent', this.handlePdaScan);
    }
  },
  methods: {
    formatDate,
    loadMore() {
      this.loading = true;
      this.param.pageNum = this.param.pageNum + 1;
      getRecevings(this.param).then(res => {
        this.listKey = Date.now();
        this.total = res.total;
        if (res.rows.length > 0) {
          res.rows.forEach(item => this.items.push(item));
        } else {
          uni.showToast({
            title: '未收货！',
            icon: 'none',
            duration: 2000
          });
          this.param.searchKey = null;
        }
        this.loading = false;
        if (this.total === 1 && this.param.pageNum === 1) {
          this.handleSubmit(res.rows[0]);
        }
      });
    },
    initScan() {
      let barcodeModel = uni.requireNativePlugin("iData-BarcodePlugin-BarcodeModule")
      barcodeModel.initScan((ret) => {
        if (ret.code === 'success') {
          console.log("初始化成功");
        }
      });
      barcodeModel.setOutputMode(4,(ret) => {
        if (ret.code === 'success') {
          console.log("模式设置成功");
        }
      });
      let globalEvent = uni.requireNativePlugin('globalEvent');
      let that = this;
      this.handlePdaScan = function(res) {
        that.checkSearchKey(res.barcode);
      }
      globalEvent.addEventListener('iDataBarcodeEvent', this.handlePdaScan);
    },
    scanCode() {
      uni.scanCode({
        success: (res) => {
          this.param.searchKey = res.result;
          this.checkSearchKey(res.result);
        },
        fail: (err) => {
          this.$modal.showToast('扫码失败', err)
        }
      });
    },
    resetDataNew() {
      this.param = {
        pageNum: 0,
        pageSize: 10,
        invCode: null,
        batchNo: null,
        suppLierName: null,
        orderNo: null,
        productionDate: null,
        searchKey: null,
      }
    },
    checkSearchKey(result) {
      this.resetDataNew();
      this.param.searchKey = result;
      this.confirmDisabled = false;
      if (result === null || result === '' || result.length < 11 || !result.toUpperCase().includes("ALL")) {
        return;
      }
      let datas = result.split("#");
      if (datas.length === 7 && result.toUpperCase().includes("ALL")) {
        this.param.invCode = datas[0];
        this.param.batchNo = datas[1];
        this.param.orderNo = datas[3];
        this.param.productionDate = datas[4];
        this.param.pageNum = 0;
        this.searchList();
      } else {
        this.$modal.showToast('扫码失败', '请扫描正确的条码' + res.result)
      }
    },
    searchList() {
      this.items = [];
      this.loadMore();
    },
    scrollTolower() {
      if (this.items.length >= this.total) {
        this.$modal.showToast("没有更多数据了");
        return;
      }
      // 计算最大页数
      let maxPage = Math.ceil(this.total / this.param.pageSize);
      if (maxPage === this.param.pageNum) {
        this.$modal.showToast("已到最后一页");
        return;
      }
      this.loadMore()
    },
    handleLongPress(row) {
      if (!(row.status === 5 || row.status === 4)) {
        this.$modal.showToast("收货后续节点任务已被执行，无法取消");
        return;
      }
      let info = '您确定要取消'+ row.invCode + '的收货记录？';
      let that = this;
      uni.showModal({
        title: '提示', // 对话框的标题
        content: info, // 对话框的内容
        success: function (res) {
          if (res.confirm) {
            cancelAsn(row).then(res => {
              let index = that.items.indexOf(row);
              if (index > -1) {
                that.items.splice(index, 1);
                that.$modal.msgSuccess("取消成功");
              }
              that.param.searchKey = null;
            });
          } else if (res.cancel) {
            // 在这里编写当用户点击取消后的逻辑代码
          }
        },
        fail: function (err) {
          console.error('显示模态对话框失败:', err);
        }
      });
    },
  },
};
</script>
<style>
.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  /* 可能需要设置一些内边距或外边距以保持良好的视觉效果 */
  padding: 10px;
  text-align: center;
  background-color: #fff; /* 背景色与页面背景色相同或透明，视设计而定 */
  z-index: 999; /* 确保按钮在最上层 */
}
.custom-list-item {
  background-color: #ADD8E6;

  /* 如果需要让整个列表项点击区域都生效，可能还需要下面这行 */
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;
  width: 100%;
  height: 100%; /* 根据实际情况调整高度 */
}

</style>
